# -*- coding:utf-8 -*-
import sys
import cv2
import os
import numpy as np
from math import *
import threading


global flag_find_paper 
global flag_move 

flag_find_paper =0
flag_move  = 0
def nothing(x):  # 滑动条的回调函数
    pass

WindowName_ball = 'Trackbar'  # 窗口名
cv2.namedWindow(WindowName_ball, cv2.WINDOW_AUTOSIZE)  # 建立空窗口
cv2.createTrackbar('h_low', WindowName_ball, 0, 10, nothing)  # 创建滑动条
cv2.createTrackbar('h_high', WindowName_ball, 160,200, nothing)  # 创建滑动条
cv2.createTrackbar('s_low', WindowName_ball, 0, 20, nothing)  # 创建滑动条
cv2.createTrackbar('s_high', WindowName_ball, 21, 255, nothing)  # 创建滑动条
cv2.createTrackbar('v_low', WindowName_ball, 0, 221, nothing)  # 创建滑动条
cv2.createTrackbar('kernel', WindowName_ball, 7, 50, nothing)  # 创建滑动条
cv2.createTrackbar('iterations', WindowName_ball, 2, 20, nothing)  # 创建滑动条

# baise:  h : 0-180   s :  0-30  v : 221-225



def get_paper(frame):
    global flag_find_paper 
    global flag_move 
    aero = 0
    gs_frame = cv2.GaussianBlur(frame, (5, 5), 0)                     # 高斯模糊
    hsv = cv2.cvtColor(gs_frame, cv2.COLOR_BGR2HSV)                 # 转化成HSV图像
    # cv2.imshow("hsv", hsv)
    h_low = cv2.getTrackbarPos('h_low', WindowName_ball)  # 获取滑动条值
    h_high = cv2.getTrackbarPos('h_high', WindowName_ball)  # 获取滑动条值
    s_low = cv2.getTrackbarPos('s_low', WindowName_ball)  # 获取滑动条值
    s_high= cv2.getTrackbarPos('s_high', WindowName_ball)  # 获取滑动条值
    v_low = cv2.getTrackbarPos('v_low', WindowName_ball)  # 获取滑动条值
    kernel = cv2.getTrackbarPos('kernel', WindowName_ball)  # 获取滑动条值
    iterations_ = cv2.getTrackbarPos('iterations', WindowName_ball)  # 获取滑动条值
    color_dist = {'white': {'Lower': np.array([h_low, s_low, v_low]), 'Upper': np.array([h_high, s_high, 255])},
                }

    erode_hsv = cv2.erode(hsv,np.ones((kernel, kernel), np.uint8), iterations=iterations_)                   # 腐蚀 粗的变细
    # cv2.imshow("erode_hsv", erode_hsv)

    # lower=np.array([0,0,221])
    # upper=np.array([180,30,255])
    # inRange_hsv_g=cv2.inRange(erode_hsv,lower,upper)   确定好hsv数据后   用这串代码   减少计算量   不卡

    inRange_hsv_g = cv2.inRange(erode_hsv, color_dist['white']['Lower'], color_dist['white']['Upper'])
    cnts_w = cv2.findContours(inRange_hsv_g.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]    #找轮廓
    cv2.imshow("inRange_hsv", inRange_hsv_g)

    if len(cnts_w)!=0:
        c_w = max(cnts_w, key=cv2.contourArea)   #找最大面积轮廓
        rect_w = cv2.minAreaRect(c_w)     #最小外接矩形框
        box_w = cv2.boxPoints(rect_w)     #矩形框四点坐标
        cv2.drawContours(frame, [np.int0(box_w)], -1, (0, 255, 0), 2)     #画框
        aero = cv2.contourArea(c_w )   #得到轮廓面积
        # print(aero)
        if aero >200000 and flag_find_paper == 0 and flag_move == 0:    #白色面积足够大（具体数值届时再算） 而且  上一状态是没有找到白纸  而且  现在魔方静止  
            print('find  paper     find  paper    find  paper   find  paper  ')
            flag_find_paper = 1
        if aero < 50000 and flag_find_paper == 1 and flag_move == 0:   #白色面积小（具体数值届时再算） 而且  上一状态是已经找到白纸  而且  现在魔方静止  
            print('move    move    move   move move    move    move   move ')
            flag_find_paper = 0
            flag_move = 1
    elif flag_find_paper == 1 and flag_move == 0:   #如果没有轮廓
        print('move    move    move   move move    move    move   move ')
        flag_find_paper = 0
        flag_move = 1
    #flag_move = 1 的时候     机械运行    运行结束后 flag_ove 记得清0  才能继续下一循环

    # cv2.imshow("img_", frame)
    #cv2.waitKey(2)


if __name__ == '__main__':
    # main()中主要做了模板匹配的操作，模板相减得到污染物位置没有做
    
    cap = cv2.VideoCapture(1)
    # cap.set(3, 1280)
    # cap.set(4, 1024)
    while True:
        secuess, fream1 = cap.read()
        if not secuess:
            print("false in reading cam")
            break
        get_paper(fream1)
        key = cv2.waitKey(10)
        if key == 27:
            break
